package com.zan.rocketmqdemo.demo;

import com.zan.rocketmqdemo.constant.MqConstant;
import com.zan.rocketmqdemo.domain.MsgModel;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.*;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author Zan
 * @Create 2024/8/29 10:50
 * @ClassName: OrderlyTest
 * @Description : 顺序消息
 */
public class OrderlyTest {

    private List<MsgModel> msgModels = Arrays.asList(
            new MsgModel("zan", 1, "下单"),
            new MsgModel("zan", 1, "短信"),
            new MsgModel("zan", 1, "物流"),

            new MsgModel("qyn", 2, "下单"),
            new MsgModel("qyn", 2, "短信"),
            new MsgModel("qyn", 2, "物流")
    );

    @Test
    public void orderlyProducer() throws Exception {
        DefaultMQProducer producer = new DefaultMQProducer("orderly-producer-group");
        producer.setNamesrvAddr(MqConstant.NAME_SRV_ADDR);
        producer.start();
        // 发送顺序消息 - 发送时要确保有序，并且要发到同一个队列下面去
        msgModels.forEach(msgModel -> {
            Message message = new Message("orderlyTopic", msgModel.toString().getBytes());
            try {
                // 发相同的订单号，去相同的队列
                producer.send(message, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        // 选择队列，arg就是我们传来的orderSn订单号
                        int hashCode = arg.toString().hashCode();
                        // 模拟长度，相同的订单号，hashCode值也一样，而mqs的长度是定值，所以就能找出对应相同的队列位置
                        int i = hashCode % mqs.size();
                        return mqs.get(i);
                    }
                }, msgModel.getOrderSn());
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

        // 关闭生产者
        producer.shutdown();
        System.out.println("发送完成");
    }

    @Test
    public void orderlyConsumer() throws Exception {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("orderly-consumer-group");
        consumer.setNamesrvAddr(MqConstant.NAME_SRV_ADDR);
        consumer.subscribe("orderlyTopic", "*");
        // MessageListenerConcurrently 是并发模式，多线程的 —— 重试 16 次
        // MessageListenerOrderly 是顺序模式，单线程的 —— 无限充实 Integer.MAX
        consumer.registerMessageListener(new MessageListenerOrderly() {
            @Override
            public ConsumeOrderlyStatus consumeMessage(List<MessageExt> msgs, ConsumeOrderlyContext context) {
                System.out.println("线程id：" + Thread.currentThread().getId());
                System.out.println(new String(msgs.get(0).getBody()));
                return ConsumeOrderlyStatus.SUCCESS;
            }
        });
        consumer.start();
        System.in.read();
    }
}
